<template>
  <div class="page-container">
    <h1>身体数据追踪</h1>
    <div class="body-stats-container">


    <!-- 添加身体数据表单 -->
    <div class="add-stats-form glass-card">
      <h2>记录今日数据</h2>
      <div class="form-grid">
        <div class="form-group">
          <label for="stats-date">日期</label>
          <input type="date" id="stats-date" v-model="newStats.date">
        </div>
        <div class="form-group">
          <label for="stats-weight">体重 (kg)</label>
          <input type="number" step="0.1" id="stats-weight" v-model.number="newStats.weight" placeholder="0.0" min="0">
        </div>
        <div class="form-group">
          <label for="stats-muscle">肌肉量 (kg)</label>
          <input type="number" step="0.1" id="stats-muscle" v-model.number="newStats.muscle" placeholder="0.0" min="0">
        </div>
        <div class="form-group">
          <label for="stats-fat">体脂率 (%)</label>
          <input type="number" step="0.1" id="stats-fat" v-model.number="newStats.fat" placeholder="0.0" min="0">
        </div>
        <div class="form-group full-width">
          <label for="stats-notes">备注</label>
          <textarea id="stats-notes" v-model="newStats.notes" rows="2" placeholder="添加备注..."></textarea>
        </div>
      </div>
      <button class="btn-primary" @click="addStats">保存数据</button>
    </div>

    <!-- 数据趋势图表 -->
    <div class="stats-charts glass-card">
      <h2>数据趋势</h2>
      <div class="chart-controls">
        <button :class="{ active: chartType === 'weight' }" @click="chartType = 'weight'">体重</button>
        <button :class="{ active: chartType === 'muscle' }" @click="chartType = 'muscle'">肌肉量</button>
        <button :class="{ active: chartType === 'fat' }" @click="chartType = 'fat'">体脂率</button>
      </div>
      <div class="chart-container">
        <!-- 图表将通过Chart.js渲染 -->
        <div class="chart-placeholder" v-if="!hasStatsData">
          暂无数据，开始记录你的身体数据吧！
        </div>
        <div class="chart-loading" v-else-if="isLoading">
          加载中...
        </div>
        <div v-else>
          <canvas id="statsChart"></canvas>
        </div>
      </div>
    </div>

    <!-- 数据记录列表 -->
    <div class="stats-records glass-card">
      <h2>历史记录</h2>
      <div class="records-table">
        <div class="table-header">
          <div class="date-col">日期</div>
          <div class="weight-col">体重 (kg)</div>
          <div class="muscle-col">肌肉量 (kg)</div>
          <div class="fat-col">体脂率 (%)</div>
          <div class="actions-col">操作</div>
        </div>
        <div v-for="(stats, index) in bodyStats" :key="index" class="table-row">
          <div class="date-col">{{ formatDate(stats.date) }}</div>
          <div class="weight-col">{{ stats.weight }}</div>
          <div class="muscle-col">{{ stats.muscle || '-' }}</div>
          <div class="fat-col">{{ stats.fat || '-' }}</div>
          <div class="actions-col">
            <button class="delete-btn" @click="deleteStats(index)">删除</button>
          </div>
        </div>
      </div>
      <div v-if="bodyStats.length === 0" class="no-records">
        <p>暂无记录</p>
      </div>
    </div>
  </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick, watch } from 'vue';
import { useBodyStatsStore } from '@/stores/bodyStats';
import { Chart, registerables } from 'chart.js';

// 注册Chart.js组件
Chart.register(...registerables);

const bodyStatsStore = useBodyStatsStore();

// 状态管理
const newStats = ref({
  date: new Date().toISOString().split('T')[0],
  weight: null,
  muscle: null,
  fat: null,
  notes: ''
});
const chartType = ref('weight');
const isLoading = ref(false);
const statsChart = ref(null);

// 从store获取身体数据
const bodyStats = computed(() => bodyStatsStore.stats);
const hasStatsData = computed(() => bodyStats.value.length > 0);

// 初始化
onMounted(() => {
  bodyStatsStore.loadStats();
  if (hasStatsData.value) {
    nextTick(() => renderChart());
  }

  // 监听数据变化重新渲染图表
bodyStatsStore.$subscribe(() => {
  if (hasStatsData.value) {
    renderChart();
  }
});

// 监听图表类型变化重新渲染
watch(chartType, () => {
  if (hasStatsData.value) {
    renderChart();
  }
});
});

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
};

// 渲染图表
const renderChart = () => {
    // 销毁现有图表
    if (statsChart.value) {
      statsChart.value.destroy();
    }

    const ctx = document.getElementById('statsChart').getContext('2d');

    // 准备图表数据
    const labels = bodyStats.value.map(stats => formatDate(stats.date));
    let data, label, borderColor, backgroundColor;

    switch(chartType.value) {
      case 'weight':
        data = bodyStats.value.map(stats => stats.weight);
        label = '体重 (kg)';
        borderColor = '#00cec9';
        backgroundColor = 'rgba(0, 206, 201, 0.1)';
        break;
      case 'muscle':
        data = bodyStats.value.map(stats => stats.muscle || 0);
        label = '肌肉量 (kg)';
        borderColor = '#74b9ff';
        backgroundColor = 'rgba(116, 185, 255, 0.1)';
        break;
      case 'fat':
        data = bodyStats.value.map(stats => stats.fat || 0);
        label = '体脂率 (%)';
        borderColor = '#ff7675';
        backgroundColor = 'rgba(255, 118, 117, 0.1)';
        break;
    }

  // 创建新图表
  statsChart.value = new Chart(ctx, {
    type: 'line',
    data: {
      labels: labels,
      datasets: [{
        label: label,
        data: data,
        borderColor: borderColor,
        backgroundColor: backgroundColor,
        tension: 0.3,
        fill: true,
        pointBackgroundColor: borderColor,
        pointRadius: 4,
        pointHoverRadius: 6
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        y: {
          beginAtZero: false,
          grid: {
            color: 'rgba(255, 255, 255, 0.1)'
          },
          ticks: {
            color: '#636e72'
          }
        },
        x: {
          grid: {
            color: 'rgba(255, 255, 255, 0.1)'
          },
          ticks: {
            color: '#636e72'
          }
        }
      },
      plugins: {
        legend: {
          labels: {
            color: '#2d3436'
          }
        }
      }
    }
  });
};

// 方法
const addStats = () => {
  if (!newStats.value.weight) {
    alert('请输入体重数据');
    return;
  }

  bodyStatsStore.addStats({
    ...newStats.value
  });

  // 重置表单
  newStats.value = {
    date: new Date().toISOString().split('T')[0],
    weight: null,
    muscle: null,
    fat: null,
    notes: ''
  };
};

const deleteStats = (index) => {
  if (confirm('确定要删除这条记录吗？')) {
    bodyStatsStore.deleteStats(index);
  }
};
</script>

<style scoped>
.page-container {
  padding: 2rem;
  margin-top: 100px;
}

.body-stats-container {
  max-width: 100%;
  display: flex;
  gap: 2rem;
  flex-wrap: wrap;
  padding-bottom: 92px;
}

h1 {
  margin-bottom: 2rem;
  color: #2d3436;
}

.page-header {
  margin-bottom: 2rem;
}

.glass-card {
  background: rgba(255, 255, 255, 0.25);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.18);
}

.add-stats-form {
  flex: 1;
  min-width: 300px;
}

.stats-charts {
  flex: 1;
  min-width: 300px;
}

.stats-records {
  flex: 1;
  min-width: 300px;
}

h1, h2 {
  color: #2d3436;
}

h2 {
  margin-bottom: 1.5rem;
  font-size: 1.5rem;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.full-width {
  grid-column: 1 / -1;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #636e72;
  font-size: 0.9rem;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 0.8rem;
  border: none;
  border-radius: 8px;
  background-color: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(5px);
}

.form-group textarea {
  resize: vertical;
}

.btn-primary {
  background-color: #00cec9;
  color: white;
  border: none;
  padding: 0.8rem 1.5rem;
  border-radius: 8px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s ease;
}

.btn-primary:hover {
  background-color: #00b8b3;
  transform: translateY(-2px);
}

.chart-controls {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.chart-controls button {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 20px;
  background-color: rgba(255, 255, 255, 0.5);
  cursor: pointer;
  transition: all 0.3s ease;
}

.chart-controls button.active {
  background-color: #00cec9;
  color: white;
}

.chart-container {
  height: 350px;
  position: relative;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 8px;
}

.chart-placeholder,
.chart-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #636e72;
}

.records-table {
  border-radius: 8px;
  overflow: hidden;
  width: 100%;
  border-collapse: collapse;
  margin-top: 1rem;
  overflow-x: auto;
  max-width: 100%;
  padding-bottom: 1rem;
  min-width: 260px;
}



.table-header {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr auto;
  background-color: rgba(255, 255, 255, 0.3);
  font-weight: bold;
  padding: 1rem;
  color: #2d3436;
}

.table-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr auto;
  padding: 1rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  color: #2d3436;
}

.table-row:last-child {
  border-bottom: none;
}

.delete-btn {
  background: none;
  border: none;
  color: #d63031;
  cursor: pointer;
  opacity: 0.7;
  transition: opacity 0.3s ease;
}

.delete-btn:hover {
  opacity: 1;
}

.no-records {
  text-align: center;
  padding: 2rem;
  color: #636e72;
}

@media (max-width: 400px) {
  .form-grid {
    grid-template-columns: 1fr;
  }
  .glass-card {
  padding: 0.75rem;
  max-width: 100%;
}
  .chart-container {
  height: 58.67vw;
  max-width: 100%;
}

.records-table {
  overflow-x: auto;
  max-width: 100%;
  padding-bottom: 1rem;
}

* {
  box-sizing: border-box;
}

.page-container {
  margin-top: 21.33vw;
  padding: 2.13vw;
}
  .records-table {
    font-size: 0.875rem;
  }
  .table-header, .table-row {
  grid-template-columns: 1fr 1fr;
  min-width: 280px;
}
  .muscle-col, .fat-col {
    display: none;
  }
}
</style>